﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SYH.Public.Model;
using System.IO;
using SYH.Utils;
using System.Data;

namespace syh876.com.Areas.User.Controllers
{
    public class ImagesController : Controller
    {
        //
        // GET: /Admin/Images/

        public ActionResult Index()
        {
            SYH.Public.BLL.Gallery ga = new SYH.Public.BLL.Gallery();
            //选择相册
            DataTable Alum = ga.GetAlum(syh876.com.Areas.User.Code.IdentityHelper.ClientUser.UserId);
            ViewBag.Alum = Alum;
            return View();
        }

        /// <summary>
        /// 创建相册  Handler/CreateAblum.aspx
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateAblum()
        {
            string name = Common.RequestHelper.GetFormString("name");
            int userId = syh876.com.Areas.User.Code.IdentityHelper.ClientUser.UserId;
            if (name != "" && Common.TypeParse.ObjectToInt(userId, 0) != 0)
            {
                SYH.Public.Model.PublicAlbum model = new SYH.Public.Model.PublicAlbum();
                model.Name = name;
                model.UserId = userId;
                int i = SYH.Public.BLL.PublicAlbum.Add(model);
                if (i > 0)
                {
                   return  Content(i.ToString());  //成功！
                }
                else
                {
                    return Content("0");  //失败!
                }

            }
            else
            {
                return Content("-1"); //失败!
            }
        }

        [HttpGet]
        public ActionResult GetImageList(int alumsId)
        {
            PagerSource ps = new PagerSource("p", 10);
            int pageCount = 0;
            int recordCount = 0;
            List<Image> list = new List<Image>();
            SYH.Public.BLL.Gallery ga = new SYH.Public.BLL.Gallery();
            list = ga.GetImages(alumsId, ps.PageSize, ps.CustomPage, out pageCount, out recordCount);
            DataTable dt = ga.GetAblumnImages(alumsId, ps.PageSize, ps.CustomPage, out pageCount, out recordCount);
            return View(dt);
        }

        [HttpPost]
        public ActionResult AlbumImgUpload(int ablumid)
        {
            try
            {
                //HttpPostedFile file;
                int width;
                int height;
                string fileName;
                HttpPostedFileBase file = Request.Files[0];
                string extesion = Path.GetExtension(file.FileName);
                if (file == null || file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) return Content("0");
                SYH.Utils.FileUploadHelper.FileUpload(file,ablumid,1, SYH.Config.ImageConfig.ImageSizeLimit, SYH.Config.ImageConfig.ImageLimitExtensions, "", out width, out height, out fileName);
                SYH.Utils.FileUploadHelper.MakeThumNail(fileName, ablumid,1);
                SYH.Public.Model.PublicAlbumImg model = new SYH.Public.Model.PublicAlbumImg();
                model.AlbumId = ablumid;
                model.Name = fileName;
                model.Size = file.ContentLength;
                model.UserId = syh876.com.Areas.User.Code.IdentityHelper.ClientUser.UserId;
                model.Title = file.FileName;
                model.Extension = extesion;
                model.Prefix = fileName.Split('.')[0];
                //如果相册没有封面则将此图设为相册封面
                if (string.IsNullOrEmpty(SYH.Public.BLL.PublicAlbum.GetModel(model.AlbumId).FrontCover))
                {
                    SYH.Public.BLL.PublicAlbum.SetCoverFile(model.AlbumId, fileName);
                }

                SYH.Public.BLL.PublicAlbumImg.Add(model);
                return Content(fileName);
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        [HttpPost]
        public ActionResult DelImg(int id,string imgName)
        {
            if (id == 0 || imgName == "")
            {
                return Content("0");
            }
            else
            {
                if (SYH.Public.BLL.PublicImageData.Delete(Common.RequestHelper.GetInt("id", 0)))
                {
                    return Content("1");
                }
                else
                {
                    return Content("0");   //失败
                }
            }
        }

        public ActionResult Album()
        {
            PagerSource ps = new PagerSource("p", 10);
            int pageCount = 0;
            int recordCount = 0;
            DataSet ds = SYH.Public.BLL.PublicAlbum.PageOrderByIdDesc(ps.PageSize, ps.CustomPage, out pageCount, out recordCount, syh876.com.Areas.User.Code.IdentityHelper.ClientUser.UserId);
  
            return View(ds.Tables[0]);
        }

        public ActionResult AlbumEdit(int id=0)
        {
            SYH.Public.Model.PublicAlbum model = SYH.Public.BLL.PublicAlbum.GetModel(id);
            if (model == null)
                model = new PublicAlbum();
            else
                ViewBag.Name = model.Name;
            return View(model);
        }

        [HttpPost]
        public ActionResult AlbumSaves(PublicAlbum model)
        {
            model = Common.ModelHelper.FillModel<PublicAlbum>(model);
            #region 执行
            if (model.Id > 0)
            {
                //if (SYH.Public.BLL.PublicAlbum.Update(model))
                //{
                //    return Content("1");
                //}
                //else
                //{
                return Content("0");
                //}
            }
            else
            {
                model.UserId = syh876.com.Areas.User.Code.IdentityHelper.ClientUser.UserId;
                string name=Request.Form["Name"];
                model.Name = name;
                if (SYH.Public.BLL.PublicAlbum.Add(model) > 0)
                {
                    return Content("1");
                }
                else
                {
                    return Content("0");
                }
            }
            #endregion
        }


        [HttpPost]
        public ActionResult AlbumSave(SYH.Public.Model.PublicAlbum model)
        {
            model = Common.ModelHelper.FillModel<PublicAlbum>(model);
            if (model.Id > 0)
            {
                if (SYH.Public.BLL.PublicAlbum.UpdateName(model.Id,model.Name))
                {
                    return Content("1");
                }
                else
                {
                    return Content("0");
                }
            }
            else
            {
                if (SYH.Public.BLL.PublicAlbum.Add(model) > 0)
                {
                    return Content("1");
                }
                else
                {
                    return Content("0");
                }
            }
        }


        public ActionResult AlbumImageDetail(int album,int id)
        {
            SYH.Public.Model.PublicAlbum info = new SYH.Public.Model.PublicAlbum();
            info = SYH.Public.BLL.PublicAlbum.GetModel(album);
            ViewBag.AlbumName = info.Name;
            ViewBag.albumId = album;

            var image = SYH.Public.BLL.PublicAlbumImg.GetModel(id);
            ViewBag.imageName = image.Name;
            ViewBag.ImageTitle = SYH.Public.BLL.PublicAlbumImg.GetTitleById(id);

            ///控制设为封面操作的显示
            if (info.FrontCover == image.Name)
            {
                ViewBag.Set = false;//设置封面
                ViewBag.Is = true;//已为封面
            }
            else
            {
                ViewBag.Set = true;//设置封面
                ViewBag.Is = false;//已为封面
            }

            ViewBag.imageurl = SYH.Utils.FileUploadHelper.GetUploadWebUrl(image.Name, SYH.Enum.ThumbImageSize.缩略图310x310);
            IList<SYH.Public.Model.PublicAlbumImg> list = SYH.Public.BLL.PublicAlbumImg.GetSimpleList(-1, " Id=" + id + " and IsDelete=0 and AlbumId = " + album);//and  UserId=4 
            return View(list);
        }

        [HttpGet]
        public ActionResult AlbumOperator(int albumId, string image)
        {
            SetCoverImage(image, albumId);

            return View();
        }

        public ActionResult RemovePic(string ids, int albumId)
        {
            removePic(ids, albumId);
            return View();
        }

        public ActionResult SetIsShows(int albumId,int value)
        {
            SetIsShow( value,albumId);
            return View();
        }

        /// <summary>
        /// 从相册中移除指定的图片
        /// </summary> 
        private void removePic(string ids, int albumId)
        {
            //string ids = Common.RequestHelper.GetString("id");
            string[] array = ids.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            try
            {
                SYH.Public.BLL.PublicAlbumImg.Delete(ids, albumId, array.Length);
                Content("1");
            }
            catch
            {
                Content("0");
            }
        }

        /// <summary>
        /// 设置相册封面
        /// </summary>
        /// <param name="context"></param>
        private void SetCoverImage(string image,int alumnId)
        {
            try
            {
                SYH.Public.BLL.PublicAlbum.SetCoverFile(alumnId, image);
                Content("1");
            }
            catch
            {
                Content("0");
            }
        }

        /// <summary>
        /// 相册权限设置
        /// </summary> 
        private void SetIsShow( int value,int alumnId)
        {
            if (SYH.Public.BLL.PublicAlbum.UpdateIsShow(alumnId, value))
            {
                Content("1");
            }
            else
            {
                Content("0");
            }
        }


        /// <summary>
        /// 修改相册名
        /// </summary>
        /// <param name="name"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AlbumImgNameEdit(string name, string id)
        {
            int result = SYH.Public.BLL.PublicAlbumImg.UpdateAlbumImgName(id, name);
            return Content(result.ToString());
        }

        [HttpPost]  //QHWUploadHandler.ashx
        public ActionResult ImageUpload(string alumsId)
        {
            try
            {
                //int userid = syh876.com.Areas.User.Code.IdentityHelper.ClientUser.UserId;
                int userid = 1;
                if (alumsId == "" || alumsId == "null")
                {
                    return Content("1");

                }
                else if (userid == 0)
                {
                    return Content("2");

                }
                else
                {
                    HttpPostedFileBase file;
                    int width;
                    int height;
                    string fileName;
                    file = Request.Files[0]; 
                    string extesion = Path.GetExtension(file.FileName);

                    if (file == null || file.ContentLength == 0 || string.IsNullOrEmpty(file.FileName)) return Content("1");

                    //上传图片
                    if (file.FileName.IndexOf(",") >= 0)
                    {
                        return Content("5");
                    }
                    else
                    {
                        Common.FileUploadHelper.FileUploadResult result = SYH.Utils.FileUploadHelper.FileUpload(file,int.Parse(alumsId),userid, SYH.Config.ImageConfig.ImageSizeLimit, SYH.Config.ImageConfig.ImageLimitExtensions, "", out width, out height, out fileName);
                        if (result == Common.FileUploadHelper.FileUploadResult.文件上传成功)
                        {
                            SYH.Utils.FileUploadHelper.MakeThumNail(fileName,int.Parse(alumsId),userid);

                            string oldUrl = SYH.Utils.FileUploadHelper.GetUploadWebUrl(fileName); //原图路径
                            string url = Common.GDI.ResizeImage(fileName, 100); //系统生成缩略图路径

                            SYH.Public.Model.PublicAlbumImg model = new SYH.Public.Model.PublicAlbumImg();
                            model.AlbumId = Convert.ToInt32(alumsId);
                            model.Name = fileName;
                            model.Size = 0;
                            model.UserId = userid;
                            model.Title = file.FileName;
                            model.Extension = Path.GetExtension(file.FileName);
                            model.Prefix = fileName.Split('.')[0];
                            int imageId = SYH.Public.BLL.PublicAlbumImg.Add(model);
                            return Content(url + "," + oldUrl + "," + imageId.ToString() + "," + Path.GetExtension(file.FileName));
                        }
                        else if (result == Common.FileUploadHelper.FileUploadResult.文件大小超过限制)
                        {
                            return Content("3");
                        }
                        else if (result == Common.FileUploadHelper.FileUploadResult.文件扩展名不允许)
                        {
                            return Content("4");
                        }
                        else
                        {
                            return Content("error");
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                //File.WriteAllText(HttpContext.Current.Server.MapPath("~/App_Data/error1.txt"), "上传图片异常：" + ex.Message.ToString() + "  " + DateTime.Now + "  |  ");
                return Content("error");
            }
        }

        public ActionResult AlbumInfo(int id)
        {
            //绑定相册基本信息
            var info = SYH.Public.BLL.PublicAlbum.GetModel(id);
            ViewBag.alumnId = id;
            ViewBag.alumnName = info.Name;
            ViewBag.picCount = info.ImgCount;
            ViewBag.coverFile = info.FrontCover;
            ViewBag.isShow = info.IsShow;
            if (string.IsNullOrEmpty(ViewBag.coverFile))
            {
                ViewBag.coverFile = SYH.Config.ImageConfig.AlumnDefaultImage;
            }
            else
            {
                ViewBag.coverFile = SYH.Utils.FileUploadHelper.GetUploadWebUrl(ViewBag.coverFile, SYH.Enum.ThumbImageSize.缩略图100x100);
            }

            bool order = true;
            if (!string.IsNullOrEmpty(Common.RequestHelper.GetString("order")))
            {
                order = (Common.RequestHelper.GetInt("order", 0) == 1) ? true : false;
            }
            //绑定相册图片列表
            PagerSource ps = new PagerSource("p", 10);
            int pageCount = 0;
            int recordCount = 0;

            DataTable dt = SYH.Public.BLL.PublicAlbumImg.GetMyPic(ViewBag.alumnId, 1, ps.CustomPage, ps.PageSize, SYH.Enum.ThumbImageSize.缩略图100x100, out pageCount, out recordCount, order);
        
            return View(dt);
        }

        public ActionResult InsertImage()
        {
            return View();
        }


        public ActionResult ImgUploadBatch()
        {
            SYH.Public.BLL.Gallery ga = new SYH.Public.BLL.Gallery();
            //选择相册
            DataTable Alum = ga.GetAlum(syh876.com.Areas.User.Code.IdentityHelper.ClientUser.UserId);
            ViewBag.Alum = Alum;
            return View();
        }

        public ActionResult ImgUploadCommon()
        {
            SYH.Public.BLL.Gallery ga = new SYH.Public.BLL.Gallery();
            //选择相册
            DataTable Alum = ga.GetAlum(syh876.com.Areas.User.Code.IdentityHelper.ClientUser.UserId);
            ViewBag.Alum = Alum;
            return View();
        }

        public ActionResult Test(int id=0)
        {
            DataTable dt = SYH.Public.BLL.PublicImageData.GetUserImgList(id, (int)SYH.Enum.ImageDataType.供应);

            return View(dt);
        }
    }
}
